﻿using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace Elderos.SqlUtils
{
    [Serializable]
    [SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize = 8000)]
    public struct Strconcat : IBinarySerialize
    {
        private List<string> _values;

        #region IBinarySerialize Members

        public void Read(BinaryReader r)
        {
            int itemCount = r.ReadInt32();
            _values = new List<string>(itemCount);
            for (int i = 0; i <= itemCount - 1; i++)
                _values.Add(r.ReadString());
        }

        public void Write(BinaryWriter w)
        {
            w.Write(_values.Count);
            foreach (string s in _values)
                w.Write(s);
        }

        #endregion

        public void Init()
        {
            _values = new List<string>();
        }

        public void Accumulate(SqlString value)
        {
            _values.Add(value.Value);
        }

        public void Merge(Strconcat value)
        {
            _values.AddRange(value._values.ToArray());
        }

        public SqlString Terminate()
        {
            return new SqlString(string.Join(", ", _values.ToArray()));
        }
    }
}